import Vue from 'vue'
import Vuex from 'vuex'
import { localRouteList, frontEndRouteList } from "../router/index.js"
import { compareRoute } from "../router/tools.js"
import * as api from "@/api/index.js"
import { getLocalStorage, uniqueObj } from "@/common.js"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    showLoadAni: false, // 是否显示页面加载进度条
    dynamicRouteList: [], // 动态路由
    tabList: [], // 小标签列表
    isLoadRoute: false, // 是否已经加载过路由
  },
  mutations: {
    setShowLoadAni(state, data) {
      state.showLoadAni = data
    },
    setDynamicRouteList(state, data) {
      state.dynamicRouteList = data
    },
    setIsLoadRoute(state, data){
      state.isLoadRoute = data
    },
    setTabList(state, data) {
      state.tabList = data
    },
  },
  actions: {
    async getRouteAsync(context){
      const roleId = getLocalStorage('roleId')
      const {list} = await api.getAccountMenu({ roleId })
      const backendRouteList = compareRoute(localRouteList, list) // 比对并生成真实路由
      let dynamicRouteList = uniqueObj([...backendRouteList, ...frontEndRouteList], 'path') // 把不在后台做的路由权限，拼接进来，并且做路由去重
      dynamicRouteList = dynamicRouteList.sort((a, b) => a.meta.sort - b.meta.sort) // 过滤出前端控制的不需要展示的路由，并且做一个排序
      const processMenu = arr => arr.length ? arr.map(v => ({...v, isSpread: true, children: processMenu(v.children || [])})) : [] // 对原始数据进行加工，新增是否展开字段
      context.commit('setDynamicRouteList', processMenu(dynamicRouteList))
      context.commit('setIsLoadRoute', true)
      // console.log(dynamicRouteList)
      return dynamicRouteList
    }
  },
  modules: {
  }
})
